#include "widget.h"
#include "ui_widget.h"
#include<QFile>
#include<QDir>
#include<QFileDialog>
#include <fstream>

#include<QMessageBox>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setFixedSize(this->width(),this->height());

}

Widget::~Widget()
{
    delete ui;
}

//上传npy文件
void Widget::on_pushButton_clicked()
{
    QString curPath = QDir::homePath();
    QString dlgTitle = "选择.npy文件";
    QString filter = "npy文件(*.npy);;所有文件(*.*)";
    QStringList fileList = QFileDialog::getOpenFileNames(this, dlgTitle, curPath, filter);

    if(fileList.isEmpty()) // 检查是否选择了文件
        return;

    foreach(const QString &aFile, fileList){
        QFileInfo fileInfo(aFile);
        QString absoluteFilePath = fileInfo.absoluteFilePath();
        QListWidgetItem *aItem = new QListWidgetItem(absoluteFilePath);
        aItem->setData(Qt::UserRole, QUrl::fromLocalFile(absoluteFilePath));
        ui->listWidget->addItem(aItem);
    }
}


//点击按钮，遍历listwidget每一项，转换为csv文件
void Widget::on_pushButton_2_clicked()
{
    if(ui->listWidget->count()==0)
        return;

    for (int i = 0; i < ui->listWidget->count(); ++i) {
        QListWidgetItem *item = ui->listWidget->item(i);
        QUrl url = item->data(Qt::UserRole).toUrl();
        QString npyFilePath = url.toLocalFile();

        // 生成CSV文件的路径，这里假设CSV文件和NPY文件在同一个目录下，并且文件名只是扩展名不同
        QString csvFilePath = npyFilePath.left(npyFilePath.lastIndexOf('.')) + ".csv";

        // 调用函数进行转换
        if (!convertNpyToCsv(npyFilePath, csvFilePath)) {
            allConverted = false;  // 如果有文件转换失败，则标记为未全部成功转换
        }
    }

    if (allConverted) {
        QMessageBox::information(this, tr("转换成功"), tr("所有文件转换成功"));
    } else {
        QMessageBox::critical(this, tr("转换错误"), tr("部分文件转换失败"));
    }
}

bool Widget::convertNpyToCsv(const QString &npyFilePath, const QString &csvFilePath)
{
    QProcess process;
    QStringList arguments;
    arguments << npyFilePath << csvFilePath;
    QString pythonScript = "F:/MyQt_pro/CppEditer/CppEditer/convert.py"; // 设置Python脚本的路径
    process.start("E:/anaconda3/python.exe",  QStringList() << pythonScript << arguments); // 启动Python进程

    process.waitForFinished();
    // 检查process.exitCode()和process.readAllStandardOutput()以获取更多信息

    if (process.exitCode() != 0) {
        return false;
    } else {
        return true;
    }
}

